package com.hu.network.http.bodyImpl;

import android.support.annotation.NonNull;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/28
 */
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class RequestBodyImpl extends RequestBody {
    private final RequestBody requestBody;
    private final ProgressListener progressListener;
    private BufferedSink bufferedSink;

    public RequestBodyImpl(RequestBody requestBody, ProgressListener progressListener) {
        this.requestBody = requestBody;
        this.progressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return this.requestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return this.requestBody.contentLength();
    }

    @Override
    public void writeTo(@NonNull BufferedSink sink) throws IOException {
        if(this.bufferedSink == null) {
            this.bufferedSink = Okio.buffer(sink(sink));
        }

        this.requestBody.writeTo(this.bufferedSink);
        this.bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            long bytesWritten = 0L;
            long contentLength = 0L;

            @Override
            public void write(@NonNull Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if(this.contentLength == 0L) {
                    this.contentLength = contentLength();
                }
                this.bytesWritten += byteCount;
                if (progressListener != null) {
                    progressListener.progress(this.bytesWritten, this.contentLength, this.bytesWritten == this.contentLength);
                }
            }
        };
    }

    public interface ProgressListener {
        void progress(long bytesRead, long contentLength, boolean done);
    }
}
